<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>系统情况 - 御物联</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        :root{
            --primary:#409EFF;
            --stage-bg:#EDE3D3; /* 全屏舞台背景（如截图外层米色） */
            --bg:#F5F7FA;      /* 页面内部背景（卡片外层浅灰） */
            --text:#303133;
            --subtext:#909399;
            --card:#FFFFFF;
            --border:#EBEEF5;
            --ok:#67C23A;
            --warn:#E6A23C;
            --danger:#F56C6C;
        }
        body{ font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif; background:var(--stage-bg); color:var(--text); }

        /* 页面容器，限制移动端阅读宽度并居中 */
        .page{ min-height:100vh; padding-bottom:calc(72px + env(safe-area-inset-bottom)); max-width:480px; margin:0 auto; background:var(--bg); }

        /* 顶部筛选更贴合触控尺寸 */
        /* 页头样式与页脚保持一致 */
        .header-box{ position:sticky; top:0; z-index:20; background:var(--card); border-bottom:1px solid var(--border); box-shadow:0 -2px 8px rgba(0,0,0,.04); padding:12px; display:flex; justify-content:space-between; align-items:center; margin:0; border-radius:0; }
        .header-box > *:first-child{ flex-shrink:0; }
        .project-select-btn{ padding:0 28px 0 14px; height:32px; border-radius:16px; background:var(--card); border:1px solid var(--border); display:inline-flex; align-items:center; gap:0; color:var(--text); box-shadow:0 1px 3px rgba(0,0,0,.03); cursor:pointer; font-size:14px; transition:all 0.2s; white-space:nowrap; width:160px; overflow:hidden; position:relative; flex-shrink:0; }
        .project-select-btn:hover{ background:var(--bg); border-color:var(--primary); color:var(--primary); }
        .project-select-btn::after{ content:'▼'; font-size:10px; position:absolute; right:10px; top:50%; transform:translateY(-50%); flex-shrink:0; z-index:2; background:var(--card); padding:0 2px; }
        .project-select-btn:hover::after{ background:var(--bg); }
        .project-select-btn span{ white-space:nowrap; display:block; overflow:hidden; text-overflow:ellipsis; max-width:calc(100% - 20px); position:relative; z-index:1; }
        .toolbar{ display:flex; justify-content:flex-end; gap:10px; padding:12px 12px 8px; position:sticky; top:0; background:linear-gradient(180deg, rgba(245,247,250,1) 70%, rgba(245,247,250,0)); z-index:10; align-items:center; }
        .select{ flex:1; height:44px; border:1px solid var(--border); border-radius:10px; background:var(--card); padding:0 12px; color:var(--text); font-size:14px; }
        .user{ padding:0 10px; height:32px; border-radius:16px; background:var(--card); border:1px solid var(--border); display:flex; align-items:center; gap:8px; color:var(--text); box-shadow:0 1px 3px rgba(0,0,0,.03); }
        .user-avatar{ width:22px; height:22px; border-radius:50%; background:var(--primary); color:#fff; display:flex; align-items:center; justify-content:center; font-size:12px; }
        .user-wrap{ position:relative; margin-left:4px; }
        .btn{ height:40px; border-radius:10px; border:1px solid var(--border); background:#fff; color:var(--text); flex:1; }
        .btn-danger{ background:#F56C6C; color:#fff; border:none; }

        /* 表单筛选区（已移出页头） */
        .filters{ display:flex; gap:10px; padding:16px 12px 10px; }

        /* 右侧抽屉面板 */
        .drawer-mask{ position:fixed; inset:0; background:rgba(0,0,0,.35); opacity:0; pointer-events:none; transition:opacity .25s ease; z-index:999; }
        .drawer-mask.open{ opacity:1; pointer-events:auto; }
        .drawer{ position:fixed; top:0; right:0; height:100vh; width:86vw; max-width:420px; background:var(--card); border-left:1px solid var(--border); box-shadow:-12px 0 24px rgba(0,0,0,.12); transform:translateX(100%); transition:transform .25s ease; z-index:1000; display:flex; flex-direction:column; }
        .drawer.open{ transform:translateX(0); }
        .drawer-header{ display:flex; align-items:center; justify-content:space-between; padding:12px 14px; border-bottom:1px solid var(--border); font-weight:600; }
        .drawer-body{ padding:0 14px 14px; color:var(--subtext); font-size:14px; overflow:auto; }
        .drawer-row{ display:flex; justify-content:space-between; padding:12px 0; border-bottom:1px solid var(--border); color:var(--text); }
        .drawer-row:last-child{ border-bottom:none; }
        .drawer-foot{ display:flex; gap:10px; padding:12px; background:var(--bg); border-top:1px solid var(--border); }

        .section-title{ padding:10px 12px; color:var(--subtext); font-size:13px; }

        .card{ background:var(--card); border:1px solid var(--border); border-radius:12px; padding:12px; margin:0 12px 10px; box-shadow:0 2px 6px rgba(0,0,0,.03); }
        .metric{ display:flex; align-items:center; justify-content:space-between; margin-bottom:6px; color:var(--subtext); font-size:12px; }
        .value{ font-size:24px; font-weight:600; color:var(--primary); line-height:1.2; }

        /* 移动端网格：默认两列，极小屏降为单列 */
        .grid{ display:grid; grid-template-columns:1fr 1fr; gap:10px; padding:0 12px 10px; }
        .grid .card{ margin:0; }
        @media (max-width:360px){ .grid{ grid-template-columns:1fr; } }

        .icon{ width:24px; height:24px; border-radius:8px; display:flex; align-items:center; justify-content:center; color:#fff; margin-left:8px; font-size:12px; }
        .icon-blue{ background:var(--primary); }
        .icon-green{ background:var(--ok); }
        .icon-orange{ background:var(--warn); }
        .icon-red{ background:var(--danger); }

        /* 底部导航：固定 + 安全区适配 */
        .footer{ position:fixed; left:0; right:0; bottom:0; height:60px; padding-bottom:env(safe-area-inset-bottom); background:var(--card); border-top:1px solid var(--border); display:flex; box-shadow:0 -2px 8px rgba(0,0,0,.04); z-index:100; }
        .footer{ max-width:480px; margin:0 auto; left:0; right:0; }
        .tab{ flex:1; display:flex; flex-direction:column; align-items:center; justify-content:center; color:var(--subtext); font-size:13px; text-decoration:none; }
        .tab.active{ color:var(--primary); font-weight:600; }
        .tab .dot{ width:6px; height:6px; border-radius:50%; background:transparent; margin-top:4px; }
        .tab.active .dot{ background:var(--primary); }
        
        /* 修改密码模态框样式 */
        .password-modal{ position:fixed; inset:0; background:rgba(0,0,0,.5); display:none; align-items:center; justify-content:center; z-index:2000; }
        .password-modal.open{ display:flex; }
        .password-dialog{ background:var(--card); border-radius:12px; padding:20px; width:90%; max-width:400px; box-shadow:0 8px 32px rgba(0,0,0,.2); }
        .password-header{ display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; }
        .password-title{ font-size:18px; font-weight:600; color:var(--text); }
        .password-close{ background:none; border:none; font-size:24px; color:var(--subtext); cursor:pointer; }
        /* .password-form{ } */
        .form-group{ margin-bottom:16px; }
        .form-label{ display:block; margin-bottom:6px; color:var(--text); font-size:14px; font-weight:500; }
        .form-input{ width:100%; height:40px; border:1px solid var(--border); border-radius:8px; padding:0 12px; font-size:14px; color:var(--text); background:var(--card); }
        .form-input:focus{ outline:none; border-color:var(--primary); box-shadow:0 0 0 2px rgba(64,158,255,.2); }
        .password-actions{ display:flex; gap:12px; margin-top:20px; }
        .btn-submit{ flex:1; height:40px; background:var(--primary); color:#fff; border:none; border-radius:8px; font-size:14px; cursor:pointer; }
        .btn-cancel{ flex:1; height:40px; background:var(--bg); color:var(--text); border:1px solid var(--border); border-radius:8px; font-size:14px; cursor:pointer; }
        .error-message{ color:var(--danger); font-size:12px; margin-top:4px; }

        /* 顶部走马灯栏 */
        .marquee-bar{
            display:flex;
            overflow-x:auto;
            white-space:nowrap;
            gap:22px;
            align-items:center;
            padding:10px 12px 0 12px;
            font-size:15px;
            background:var(--bg);
            min-height:38px;
        }
        .marquee-item{ display:inline-flex; align-items:center; gap:8px; opacity:0.76; }
        .marquee-item b{ color:var(--primary); font-size:20px; margin:0 3px; }
        .marquee-item .icon{ width:22px; height:22px; min-width:22px; min-height:22px; font-size:17px; border-radius:5px; display:inline-flex; justify-content:center; align-items:center; }

        /* 优化marquee-flip为竖向滑动淡入出动画 */
        .marquee-flip { min-height:52px; display:flex; align-items:center; justify-content:center; background:var(--bg); margin-bottom:0.5em; overflow:hidden; position:relative; }
        .flip-group {
            display: flex; flex-direction: column; gap: 4px; width: 100%; opacity: 0;
            pointer-events: none; position: absolute; left: 0; right: 0; top: 0; z-index:0;
            transition: opacity 0.6s cubic-bezier(0.42,0,0.58,1), transform 0.6s cubic-bezier(0.42,0,0.58,1);
            transform: translateY(30%); /* 初始下方起 */
        }
        .flip-group.active {
            opacity: 1; pointer-events: auto; position: relative; z-index:1;
            transform: translateY(0); /* 完全滑入 */
        }
        .flip-item {
            font-size: 15px; color: var(--text); display: flex; gap: 10px; align-items: center;
            background: rgba(255,255,255,.96); border-radius: 12px; margin: 2px 14px; padding: 9px 16px 9px 10px; box-shadow: 0 2px 7px #bbc2d80e; font-weight: 400;
        }
        .flip-item .icon { width: 20px; height: 20px; font-size: 17px; border-radius: 5px; display: inline-flex; justify-content: center; align-items: center; }

        /* 分区统一样式 */
        .quick-section{ margin-top:28px; padding:0 18px; margin-bottom:20px; }
        .quick-section:last-child{ margin-bottom:90px; } /* 最后一个区块增加底部间距，避免被导航栏遮盖 */
        .quick-section-card{
            position:relative; padding:20px 18px 18px; border-radius:28px;
            background:linear-gradient(165deg, rgba(255,255,255,.98) 0%, rgba(236,242,255,.95) 100%);
            box-shadow:0 18px 36px rgba(82,120,179,.18);
            overflow:hidden;
        }
        .quick-section-card::before{
            content:""; position:absolute; inset:0; border-radius:inherit;
            background:radial-gradient(120% 90% at 0% 0%, rgba(64,158,255,.18), transparent 60%);
            pointer-events:none;
        }
        .quick-section-card > *{ position:relative; z-index:1; }
        .quick-section-header{ display:flex; justify-content:space-between; align-items:center; padding:0 2px 10px; }
        .quick-title{ font-size:18px; font-weight:700; color:var(--text); letter-spacing:0.3px; }
        .quick-section-actions{ display:flex; align-items:center; gap:10px; }
        .section-action-btn{
            height:34px; padding:0 18px; border-radius:18px; border:1px solid rgba(64,158,255,.18);
            background:rgba(255,255,255,.92); color:var(--primary); font-size:13px; font-weight:600;
            display:flex; align-items:center; justify-content:center; box-shadow:0 10px 20px rgba(64,158,255,.12);
            transition:transform .18s, box-shadow .18s; cursor:pointer;
        }
        .section-action-btn.outline{ color:var(--subtext); border-color:rgba(0,0,0,.05); box-shadow:0 8px 18px rgba(31,45,61,.08); }
        .section-action-btn.primary{ background:var(--primary); color:#fff; border-color:var(--primary); box-shadow:0 14px 26px rgba(64,158,255,.38); }
        .section-action-btn:disabled{ opacity:.45; pointer-events:none; box-shadow:none; }
        .section-action-btn:not(:disabled):active{ transform:translateY(1px); }

        /* 场景卡片区 - 横向滚动 */
        .scene-quick-scroll{ display:flex; gap:16px; overflow-x:auto; margin:0 -2px; padding-bottom:6px; scroll-snap-type:x mandatory; cursor:grab; }
        .scene-quick-scroll::-webkit-scrollbar{ display:none; }
        .scene-card{
            flex:0 0 160px; min-height:126px;
            background:rgba(255,255,255,.92); border-radius:20px; border:1px solid rgba(255,255,255,.65);
            box-shadow:0 14px 28px rgba(109,133,182,.18);
            display:flex; flex-direction:column; gap:10px; padding:18px 16px 16px;
            transition:transform .2s, box-shadow .2s; cursor:pointer; scroll-snap-align:start;
        }
        .scene-quick-scroll.dragging{ cursor:grabbing; }
        .scene-card:active,.scene-card:focus{ box-shadow:0 20px 36px rgba(64,158,255,.28); transform:translateY(-4px); }
        .scene-title{ font-size:16px; font-weight:700; color:var(--text); }
        .scene-desc{ color:var(--subtext); font-size:13px; line-height:1.45; }
        .scene-action{
            margin-top:auto; height:34px; border-radius:18px; border:none;
            background:var(--primary); color:#fff; font-size:14px; font-weight:600;
            display:flex; align-items:center; justify-content:center;
            box-shadow:0 10px 22px rgba(64,158,255,.26); cursor:pointer; transition:transform .15s;
        }
        .scene-action:active{ transform:scale(.96); }

        /* 快捷控制区 - 横向滚动与多选态 */
        .control-quick-scroll{ display:flex; gap:12px; overflow-x:auto; margin:4px -2px 0; padding-bottom:8px; scroll-snap-type:x mandatory; cursor:grab; }
        .control-quick-scroll::-webkit-scrollbar{ display:none; }
        .control-quick-scroll.dragging{ cursor:grabbing; }
        .control-card{
            flex:0 0 170px;
            background:linear-gradient(186deg, rgba(255,255,255,.97) 0%, rgba(233,240,255,.9) 100%);
            border-radius:18px; border:1px solid rgba(64,158,255,.08);
            box-shadow:0 14px 28px rgba(82,120,179,.16);
            padding:12px 14px 14px;
            display:flex; flex-direction:column; gap:10px;
            position:relative; scroll-snap-align:start; cursor:default;
            transition:box-shadow .22s, transform .22s, border-color .22s;
        }
        .control-card:hover{ box-shadow:0 18px 32px rgba(64,158,255,.22); }
        .control-title{ font-size:15px; font-weight:700; color:var(--text); }
        .control-subtitle{ font-size:11px; color:var(--subtext); }
        .control-footer{ display:flex; justify-content:flex-end; }
        .control-btn{
            height:30px; padding:0 16px; border-radius:15px; border:none;
            background:var(--primary); color:#fff; font-size:12px; font-weight:600;
            box-shadow:0 8px 18px rgba(64,158,255,.24); cursor:pointer; transition:transform .15s;
        }
        .control-btn:active{ transform:scale(.95); }
        
        /* Switch 开关样式 */
        .control-switch-container{ display:flex; align-items:center; justify-content:center; margin-top:8px; }
        .control-switch-large{ position:relative; width:90px; height:48px; }
        .control-switch-track{ width:100%; height:100%; background:#67C23A; border-radius:24px; position:relative; cursor:pointer; transition:background 0.3s; box-shadow:inset 0 2px 4px rgba(0,0,0,.1); }
        .control-switch-track.off{ background:#dcdfe6; }
        .control-switch-handle{ position:absolute; top:4px; left:4px; width:40px; height:40px; background:#fff; border-radius:50%; transition:transform 0.3s ease; box-shadow:0 2px 6px rgba(0,0,0,.2); }
        .control-switch-track.off .control-switch-handle{ transform:translateX(0); }
        .control-switch-track.on .control-switch-handle{ transform:translateX(42px); }
 
        /* 快捷数据卡片区 */
        .data-quick-list{
            background:rgba(255,255,255,.9); border-radius:20px; border:1px solid rgba(255,255,255,.65);
            box-shadow:inset 0 1px 0 rgba(255,255,255,.7);
            margin:8px 0 0; padding:12px 0;
            max-height:280px; overflow-y:auto; overflow-x:hidden;
            -webkit-overflow-scrolling:touch; /* iOS 平滑滚动 */
        }
        .data-quick-list::-webkit-scrollbar{
            width:4px;
        }
        .data-quick-list::-webkit-scrollbar-track{
            background:transparent;
        }
        .data-quick-list::-webkit-scrollbar-thumb{
            background:rgba(64,158,255,.2); border-radius:2px;
        }
        .data-quick-list::-webkit-scrollbar-thumb:hover{
            background:rgba(64,158,255,.35);
        }
        .data-row{display:flex;justify-content:space-between;align-items:center;padding:12px 20px;font-size:15px;border-bottom:1px solid rgba(236,240,255,.8);position:relative;transition:background-color 0.3s ease;}
        .data-row:last-child{border-bottom:none;}
        .data-name{color:var(--text);font-weight:500;}
        .data-value{color:var(--primary);font-size:16px;min-width:72px;white-space:nowrap;font-variant-numeric:tabular-nums;font-weight:600;position:relative;transition:transform 0.3s ease, color 0.3s ease;}
        
        /* 数据更新动画效果 */
        .data-row.updating{
            animation:dataRowUpdate 0.8s ease;
        }
        .data-value.updating{
            animation:valueUpdate 0.6s ease;
        }
        @keyframes dataRowUpdate{
            0%{ background-color:transparent; }
            50%{ background-color:rgba(64,158,255,.12); }
            100%{ background-color:transparent; }
        }
        @keyframes valueUpdate{
            0%{ transform:scale(1); color:var(--primary); }
            30%{ transform:scale(1.15); color:#66b1ff; }
            60%{ transform:scale(1.08); color:#85c1ff; }
            100%{ transform:scale(1); color:var(--primary); }
        }
        
        /* 数据区域整体更新提示 */
        .data-quick-list.updating{
            animation:dataListUpdate 1s ease;
        }
        @keyframes dataListUpdate{
            0%{ box-shadow:0 0 0 rgba(64,158,255,0); }
            50%{ box-shadow:0 0 20px rgba(64,158,255,.3), inset 0 0 10px rgba(64,158,255,.1); }
            100%{ box-shadow:0 0 0 rgba(64,158,255,0); }
        }

        /* 项目选择列表样式 */
        .project-list-item{
            padding:14px 16px; background:var(--bg); border-radius:10px; border:1px solid var(--border);
            margin-bottom:10px; cursor:pointer; transition:background .2s, border-color .2s;
        }
        .project-list-item:hover{ background:rgba(64,158,255,.08); border-color:var(--primary); }
        .project-list-item.selected{ background:rgba(64,158,255,.12); border-color:var(--primary); }
        .project-list-name{ font-size:15px; font-weight:600; color:var(--text); margin-bottom:4px; }
        .project-list-short{ font-size:12px; color:var(--subtext); }
        /* 控制面板弹窗样式 */
        .modal-mask{ position:fixed; inset:0; background:rgba(0,0,0,.45); opacity:0; pointer-events:none; transition:opacity .25s ease; z-index:2000; }
        .modal-mask.open{ opacity:1; pointer-events:auto; }
        .modal-dialog{ position:fixed; top:50%; left:50%; transform:translate(-50%, -48%) scale(.92); background:var(--card); border-radius:16px; width:88vw; max-width:380px; box-shadow:0 18px 40px rgba(31,45,61,.28); transition:transform .25s ease; }
        .modal-mask.open .modal-dialog{ transform:translate(-50%, -50%) scale(1); }
        .modal-header{ padding:20px 20px 0; display:flex; align-items:center; justify-content:space-between; }
        .modal-title{ font-size:18px; font-weight:700; color:var(--text); }
        .modal-close{ width:28px; height:28px; border:none; background:none; font-size:20px; color:var(--subtext); cursor:pointer; }
        .modal-body{ padding:18px 20px 12px; }
        .modal-footer{ padding:0 20px 20px; display:flex; gap:12px; }
        .modal-btn{ flex:1; height:42px; border-radius:12px; border:1px solid var(--border); background:var(--bg); color:var(--text); font-size:15px; cursor:pointer; }
        .modal-btn.primary{ background:var(--primary); border-color:var(--primary); color:#fff; }
        .modal-btn.success{ background:var(--ok); border-color:var(--ok); color:#fff; }
        .modal-btn.danger{ background:var(--danger); border-color:var(--danger); color:#fff; }
        .switch-group{ display:flex; gap:14px; }
        .switch-group .modal-btn{ height:48px; font-size:16px; font-weight:600; }
        .aircon-section{ display:flex; flex-direction:column; gap:18px; }
        .mode-buttons{ display:flex; gap:10px; justify-content:center; }
        .mode-buttons .modal-btn{ flex:1; height:36px; font-size:14px; }
        .temp-controls{ display:flex; align-items:center; justify-content:center; gap:18px; }
        .temp-display{ font-size:26px; font-weight:700; color:var(--primary); min-width:70px; text-align:center; }
        .progress-control{ display:flex; flex-direction:column; gap:16px; }
        .progress-container{ position:relative; height:8px; border-radius:4px; background:var(--border); }
        .progress-bar{ position:absolute; inset:0 auto 0 0; background:var(--primary); border-radius:4px; width:50%; }
        .progress-handle{ position:absolute; top:50%; transform:translate(-50%, -50%); width:20px; height:20px; border-radius:50%; background:var(--primary); border:3px solid #fff; box-shadow:0 3px 10px rgba(64,158,255,.32); cursor:pointer; left:50%; }
        .progress-value{ text-align:center; font-size:18px; font-weight:600; color:var(--primary); }
        
        /* 管理控制列表样式 */
        .manage-control-list{ display:flex; flex-direction:column; gap:10px; }
        .manage-control-item{
            display:flex; justify-content:space-between; align-items:center;
            padding:14px; background:var(--bg); border-radius:10px; border:1px solid var(--border);
        }
        .manage-control-info{ flex:1; }
        .manage-control-name{ font-size:15px; font-weight:600; color:var(--text); margin-bottom:4px; }
        .manage-control-type{ font-size:12px; color:var(--subtext); }
        .manage-control-delete{
            width:32px; height:32px; border:none; background:var(--danger); color:#fff;
            border-radius:8px; font-size:16px; cursor:pointer; display:flex;
            align-items:center; justify-content:center; transition:opacity .2s;
        }
        .manage-control-delete:active{ opacity:.7; }
        
        /* 设备选择列表样式 */
        .device-select-item{
            padding:14px; background:var(--bg); border-radius:10px; border:1px solid var(--border);
            margin-bottom:10px; cursor:pointer; transition:background .2s, border-color .2s;
        }
        .device-select-item:hover{ background:rgba(64,158,255,.08); border-color:var(--primary); }
        .device-select-item.disabled{
            opacity:.5; cursor:not-allowed; background:var(--bg);
        }
        .device-select-name{ font-size:15px; font-weight:600; color:var(--text); margin-bottom:6px; }
        .device-select-controls{ display:flex; flex-wrap:wrap; gap:6px; }
        .device-control-badge{
            padding:4px 10px; background:rgba(64,158,255,.12); color:var(--primary);
            border-radius:12px; font-size:12px; font-weight:500;
        }
    </style>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
</head>
<body>
    <div class="page">
        <!-- 白色吸顶框包含用户信息 -->
        <div class="header-box">
            <button class="project-select-btn" id="projectSelectBtn" type="button" title="选择项目">
                <span id="projectSelectText">物测</span>
            </button>
            <button class="user" id="userBtn" type="button" title="查看个人信息">
                <span class="user-avatar" id="userAvatar">U</span>
                <span id="userName">用户</span>
            </button>
        </div>

        <!-- 自动翻转统计栏：每次只显示一条 -->
        <div class="marquee-flip" id="marqueeFlip">
            <div class="flip-group active"><div class="flip-item"><span class="icon icon-blue">🛡️</span> 网关 <b>3</b> | 在线 <b>2</b> 离线 <b>1</b></div></div>
            <div class="flip-group"><div class="flip-item"><span class="icon icon-blue">📡</span> 传感器 <b>40</b> | 在线 <b>35</b> 离线 <b>5</b></div></div>
            <div class="flip-group"><div class="flip-item"><span class="icon icon-red">🚨</span> 今日告警 <b>5</b> | 未处理 <b>2</b></div></div>
            <div class="flip-group"><div class="flip-item"><span class="icon icon-green">📥</span> 今日下发命令 <b>16</b></div></div>
        </div>

        <div class="quick-section">
            <div class="quick-section-card">
                <div class="quick-section-header">
                    <div class="quick-title">一键场景</div>
                    <div class="quick-section-actions">
                        <button type="button" class="section-action-btn outline" id="sceneManageBtn">自定义场景</button>
                    </div>
                </div>
                <div class="scene-quick-scroll" id="sceneQuickScroll">
                    <div class="scene-card" data-scene="回家模式">
                        <div class="scene-title">回家模式</div>
                        <div class="scene-desc">灯光、空调提前设定，营造温馨氛围</div>
                        <button type="button" class="scene-action">执行场景</button>
                    </div>
                    <div class="scene-card" data-scene="离家模式">
                        <div class="scene-title">离家模式</div>
                        <div class="scene-desc">一键关闭主要设备，保持安防在线</div>
                        <button type="button" class="scene-action">执行场景</button>
                    </div>
                    <div class="scene-card" data-scene="办公模式">
                        <div class="scene-title">办公模式</div>
                        <div class="scene-desc">根据工位开启照明与空调，保持舒适</div>
                        <button type="button" class="scene-action">执行场景</button>
                    </div>
                    <div class="scene-card" data-scene="夜间巡检">
                        <div class="scene-title">夜间巡检</div>
                        <div class="scene-desc">低亮照明+安防巡检，确保安全节能</div>
                        <button type="button" class="scene-action">执行场景</button>
                    </div>
                </div>
            </div>
            </div>

        <!-- 快捷控制器操作区 -->
        <div class="quick-section">
            <div class="quick-section-card">
                <div class="quick-section-header">
                    <div class="quick-title">快速操作</div>
                    <div class="quick-section-actions">
                        <button type="button" class="section-action-btn outline" id="controlManageBtn">自定义控制</button>
            </div>
            </div>
                <div class="control-quick-scroll" id="controlQuickScroll">
                    <!-- 控制卡片将动态生成 -->
            </div>
            </div>
        </div>

        <!-- 快捷数据关注区 -->
        <div class="quick-section">
            <div class="quick-section-card quick-section-card--data">
                <div class="quick-section-header">
                    <div class="quick-title">数据看板</div>
                    <div class="quick-section-actions">
                        <button type="button" class="section-action-btn outline" id="dataManageBtn">自定义数据</button>
                    </div>
                </div>
                <div class="data-quick-list" id="dataQuickList">
                    <!-- 数据列表将动态生成 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 固定底部导航 -->
    <nav class="footer">
        <a class="tab active" href="system-overview.html" aria-current="page">
            <span>首页</span>
            <span class="dot"></span>
        </a>
        <a class="tab" href="device-list.html">
            <span>设备</span>
            <span class="dot"></span>
        </a>
        <a class="tab" href="alarm-list.html">
            <span>告警</span>
            <span class="dot"></span>
        </a>
    </nav>

    <!-- 个人信息右侧抽屉 -->
    <div class="drawer-mask" id="drawerMask"></div>
    <aside class="drawer" id="userDrawer" aria-label="个人信息">
        <div class="drawer-header">
            <span>个人信息</span>
        </div>
        <div class="drawer-body">
            <div class="drawer-row" style="padding:20px 0 12px; text-align:center;">
                <button id="userInfoBtn" class="btn btn-primary" style="width:100%; height:48px; font-size:16px;">查看个人信息</button>
            </div>
            <div class="drawer-row" style="border-bottom:none; padding:12px 0 20px; text-align:center;">
                <button id="controlPanelBtn" class="btn" style="width:100%; height:48px; font-size:16px; background:var(--ok); color:#fff; border-color:var(--ok);">操作面板展示</button>
            </div>
        </div>
        <div class="drawer-foot">
            <button id="changePasswordBtn" class="btn" style="flex:1; background:var(--primary); color:#fff; border:none;">修改密码</button>
            <button id="logoutBtn" class="btn-danger" style="flex:1;">退出登录</button>
            <button id="closePanel" class="btn" style="flex:1;">关闭</button>
        </div>
    </aside>

    <!-- 修改密码模态框 -->
    <div class="password-modal" id="passwordModal">
        <div class="password-dialog">
            <div class="password-header">
                <span class="password-title">修改密码</span>
                <button class="password-close" id="passwordClose">&times;</button>
            </div>
            <form class="password-form" id="passwordForm">
                <div class="form-group">
                    <label class="form-label" for="currentPassword">当前密码</label>
                    <input type="password" class="form-input" id="currentPassword" placeholder="请输入当前密码" required>
                    <div class="error-message" id="currentPasswordError"></div>
                </div>
                <div class="form-group">
                    <label class="form-label" for="newPassword">新密码</label>
                    <input type="password" class="form-input" id="newPassword" placeholder="请输入新密码" required>
                    <div class="error-message" id="newPasswordError"></div>
                </div>
                <div class="form-group">
                    <label class="form-label" for="confirmPassword">确认新密码</label>
                    <input type="password" class="form-input" id="confirmPassword" placeholder="请再次输入新密码" required>
                    <div class="error-message" id="confirmPasswordError"></div>
                </div>
                <div class="password-actions">
                    <button type="button" class="btn-cancel" id="passwordCancel">取消</button>
                    <button type="submit" class="btn-submit">确认修改</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 控制面板弹窗 -->
    <div class="modal-mask" id="switchModal">
        <div class="modal-dialog">
            <div class="modal-header">
                <div class="modal-title">开关控制</div>
                <button class="modal-close" data-close="switchModal">×</button>
            </div>
            <div class="modal-body" style="padding:60px 20px;">
                <div style="display:flex; flex-direction:column; justify-content:center; align-items:center; gap:20px;">
                    <div class="control-switch-large">
                        <div class="control-switch-track on" id="switchToggle">
                            <div class="control-switch-handle"></div>
                        </div>
                    </div>
                    <div id="switchStatus" style="font-size:16px; color:var(--text); font-weight:500;">当前状态：开启</div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn" data-close="switchModal" style="flex:1;">关闭</button>
            </div>
        </div>
    </div>

    <div class="modal-mask" id="airconModal">
        <div class="modal-dialog">
            <div class="modal-header">
                <div class="modal-title">红外遥控器控制面板</div>
                <button class="modal-close" data-close="airconModal">×</button>
            </div>
            <div class="modal-body aircon-section">
                <div style="text-align:center; color:var(--subtext); font-size:12px; margin-bottom:16px; padding:10px; background:rgba(255,193,7,.1); border-radius:8px;">
                    ⚠️ 注意：不能获取实时控制数据
                </div>
                <div id="airconTempDisplay" style="text-align:center; margin-bottom:16px; padding:12px; background:rgba(64,158,255,.1); border-radius:8px; color:var(--primary); font-weight:600; display:none;">
                    当前温度：25°C
                </div>
                <div class="switch-group">
                    <button class="modal-btn success" data-aircon-power="on">打开空调</button>
                    <button class="modal-btn danger" data-aircon-power="off">关闭空调</button>
                </div>
                <div style="text-align:center; color:var(--subtext);">温度调节</div>
                <div class="temp-controls">
                    <button class="modal-btn" data-aircon-temp="-1" style="width:44px; border-radius:50%; font-size:20px;">-</button>
                    <div class="temp-display" id="airconTemp">25°C</div>
                    <button class="modal-btn" data-aircon-temp="1" style="width:44px; border-radius:50%; font-size:20px;">+</button>
                </div>
                <div style="text-align:center; color:var(--subtext);">工作模式</div>
                <div class="mode-buttons">
                    <button class="modal-btn primary" data-aircon-mode="cool" id="airconCoolBtn">制冷</button>
                    <button class="modal-btn" data-aircon-mode="heat" id="airconHeatBtn">制热</button>
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn" data-close="airconModal">取消</button>
                <button class="modal-btn primary" id="airconSaveBtn">保存</button>
            </div>
        </div>
    </div>

    <div class="modal-mask" id="openingModal">
        <div class="modal-dialog">
            <div class="modal-header">
                <div class="modal-title">开度控制</div>
                <button class="modal-close" data-close="openingModal">×</button>
            </div>
            <div class="modal-body">
                <div class="progress-control">
                    <div class="progress-container" id="openingTrack">
                        <div class="progress-bar" id="openingBar"></div>
                        <div class="progress-handle" id="openingHandle" style="left:0%"></div>
                    </div>
                    <div class="progress-value" id="openingValue">0%</div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn" data-close="openingModal" style="flex:1;">关闭</button>
            </div>
        </div>
    </div>

    <!-- 亮度控制弹窗 -->
    <div class="modal-mask" id="brightnessModal">
        <div class="modal-dialog">
            <div class="modal-header">
                <div class="modal-title">亮度控制</div>
                <button class="modal-close" data-close="brightnessModal">×</button>
            </div>
            <div class="modal-body">
                <div class="progress-control">
                    <div class="progress-label">亮度调节</div>
                    <div class="progress-container" id="brightnessContainer">
                        <div class="progress-bar" id="brightnessBar" style="width: 50%;"></div>
                        <div class="progress-handle" id="brightnessHandle" style="left: 50%;"></div>
                    </div>
                    <div class="progress-value" id="brightnessValue">50%</div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn" data-close="brightnessModal">关闭</button>
            </div>
        </div>
    </div>

    <!-- 管理控制弹窗 -->
    <div class="modal-mask" id="controlManageModal">
        <div class="modal-dialog" style="max-width:420px;">
            <div class="modal-header">
                <div class="modal-title">管理控制</div>
                <button class="modal-close" data-close="controlManageModal">×</button>
            </div>
            <div class="modal-body">
                <div class="manage-control-list" id="manageControlList">
                    <!-- 动态生成的控制列表 -->
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn" data-close="controlManageModal">关闭</button>
                <button class="modal-btn primary" id="addControlBtn">添加控制</button>
            </div>
        </div>
    </div>

    <!-- 设备选择弹窗 -->
    <div class="modal-mask" id="deviceSelectModal">
        <div class="modal-dialog" style="max-width:420px;">
            <div class="modal-header">
                <div class="modal-title">选择设备</div>
                <button class="modal-close" data-close="deviceSelectModal">×</button>
            </div>
            <div class="modal-body">
                <div style="margin-bottom:12px;">
                    <input type="text" id="deviceSearchInput" placeholder="搜索设备名称..." style="width:100%; height:40px; border:1px solid var(--border); border-radius:8px; padding:0 12px; font-size:14px;">
                </div>
                <div class="device-select-list" id="deviceSelectList" style="max-height:400px; overflow-y:auto;">
                    <!-- 动态生成的设备列表 -->
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn" data-close="deviceSelectModal">取消</button>
            </div>
        </div>
    </div>

    <!-- 管理数据弹窗 -->
    <div class="modal-mask" id="dataManageModal">
        <div class="modal-dialog" style="max-width:420px;">
            <div class="modal-header">
                <div class="modal-title">管理数据</div>
                <button class="modal-close" data-close="dataManageModal">×</button>
            </div>
            <div class="modal-body">
                <div class="manage-control-list" id="manageDataList">
                    <!-- 动态生成的数据列表 -->
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn" data-close="dataManageModal">关闭</button>
                <button class="modal-btn primary" id="addDataBtn">添加数据</button>
            </div>
        </div>
    </div>

    <!-- 数据传感器选择弹窗 -->
    <div class="modal-mask" id="dataSensorSelectModal">
        <div class="modal-dialog" style="max-width:420px;">
            <div class="modal-header">
                <div class="modal-title">选择数据传感器</div>
                <button class="modal-close" data-close="dataSensorSelectModal">×</button>
            </div>
            <div class="modal-body">
                <div style="margin-bottom:12px;">
                    <input type="text" id="dataSensorSearchInput" placeholder="搜索设备或传感器..." style="width:100%; height:40px; border:1px solid var(--border); border-radius:8px; padding:0 12px; font-size:14px;">
                </div>
                <div class="device-select-list" id="dataSensorSelectList" style="max-height:400px; overflow-y:auto;">
                    <!-- 动态生成的数据传感器列表 -->
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn" data-close="dataSensorSelectModal">取消</button>
            </div>
        </div>
    </div>

    <!-- 项目选择弹窗 -->
    <div class="modal-mask" id="projectSelectModal">
        <div class="modal-dialog" style="max-width:420px;">
            <div class="modal-header">
                <div class="modal-title">选择项目</div>
                <button class="modal-close" data-close="projectSelectModal">×</button>
            </div>
            <div class="modal-body">
                <div class="device-select-list" id="projectSelectList" style="max-height:400px; overflow-y:auto;">
                    <!-- 动态生成的项目列表 -->
                </div>
            </div>
            <div class="modal-footer">
                <button class="modal-btn" data-close="projectSelectModal">取消</button>
            </div>
        </div>
    </div>

    <script>
        // footer 跳转已直接使用链接

        // 初始化用户信息显示
        (function initUser(){
            try {
                const userStr = localStorage.getItem('currentUser');
                const user = userStr ? JSON.parse(userStr) : null;
                const nameEl = document.getElementById('userName');
                const avatarEl = document.getElementById('userAvatar');
                if(user){
                    nameEl.textContent = user.name || '用户';
                    avatarEl.textContent = (user.name || 'U').slice(0,1);
                }
            } catch(e){}
        })();

        // 项目选择功能
        (function(){
            const STORAGE_KEY = 'selectedProject';
            const projectSelectBtn = document.getElementById('projectSelectBtn');
            const projectSelectText = document.getElementById('projectSelectText');
            const projectSelectModal = document.getElementById('projectSelectModal');
            const projectSelectList = document.getElementById('projectSelectList');
            
            // 项目数据（名称和简称，简称应为四字或五字，如果没有简称则显示全称）
            const projects = [
                { id: '1', name: '物联网内部测试系统', short: '物联网测试系统' },
                { id: '2', name: '智慧园区示范点', short: '智慧园区示范' },
                { id: '3', name: '城市水务试点', short: '城市水务试点' },
                { id: '4', name: '智能办公大楼物联网控制系统' } // 没有简称，将显示全称
            ];
            
            // 获取当前选中的项目
            function getSelectedProject(){
                const saved = localStorage.getItem(STORAGE_KEY);
                if(saved){
                    try{
                        const selected = JSON.parse(saved);
                        return projects.find(p => p.id === selected.id) || projects[0];
                    }catch(e){
                        console.error('解析项目数据失败', e);
                    }
                }
                return projects[0]; // 默认第一个
            }
            
            // 保存选中的项目
            function saveSelectedProject(project){
                localStorage.setItem(STORAGE_KEY, JSON.stringify({ id: project.id }));
            }
            
            // 更新显示文本
            function updateDisplayText(){
                const selected = getSelectedProject();
                // 如果有简称则显示简称，否则显示全称（即使显示不全也可以）
                projectSelectText.textContent = selected.short || selected.name;
            }
            
            // 渲染项目列表
            function renderProjectList(){
                const selected = getSelectedProject();
                projectSelectList.innerHTML = '';
                
                projects.forEach(project => {
                    const item = document.createElement('div');
                    item.className = 'project-list-item';
                    if(project.id === selected.id){
                        item.classList.add('selected');
                    }
                    
                    item.innerHTML = `
                        <div class="project-list-name">${project.name}</div>
                        <div class="project-list-short">${project.short ? `简称：${project.short}` : '（无简称，显示全称）'}</div>
                    `;
                    
                    item.addEventListener('click', () => {
                        saveSelectedProject(project);
                        updateDisplayText();
                        renderProjectList();
                        closeProjectModal();
                        // 这里可以添加项目切换后的其他逻辑
                    });
                    
                    projectSelectList.appendChild(item);
                });
            }
            
            // 打开/关闭弹窗
            function openProjectModal(){
                renderProjectList();
                projectSelectModal.classList.add('open');
            }
            
            function closeProjectModal(){
                projectSelectModal.classList.remove('open');
            }
            
            // 事件监听
            projectSelectBtn.addEventListener('click', openProjectModal);
            
            // 关闭弹窗按钮
            document.querySelectorAll('[data-close="projectSelectModal"]').forEach(btn => {
                btn.addEventListener('click', closeProjectModal);
            });
            
            // 点击遮罩关闭弹窗
            projectSelectModal.addEventListener('click', (e) => {
                if(e.target === projectSelectModal) closeProjectModal();
            });
            
            // 初始化显示
            updateDisplayText();
        })();

        // 右侧抽屉交互
        const drawer = document.getElementById('userDrawer');
        const mask = document.getElementById('drawerMask');
        function openDrawer(){ drawer.classList.add('open'); mask.classList.add('open'); }
        function closeDrawer(){ drawer.classList.remove('open'); mask.classList.remove('open'); }
        document.getElementById('userBtn').addEventListener('click', openDrawer);
        document.getElementById('closePanel').addEventListener('click', closeDrawer);
        mask.addEventListener('click', closeDrawer);
        document.getElementById('userInfoBtn').addEventListener('click', () => {
            closeDrawer();
            window.location.href = 'user-info.html';
        });
        document.getElementById('controlPanelBtn').addEventListener('click', () => {
            closeDrawer();
            window.location.href = 'control-panel-demo.html';
        });
        document.getElementById('logoutBtn').addEventListener('click', () => {
            localStorage.removeItem('currentUser');
            window.location.href = 'mobile-login-demo.html';
        });
        // Esc 关闭
        document.addEventListener('keydown', (e)=>{ if(e.key==='Escape') closeDrawer(); });
        
        // 修改密码功能
        const passwordModal = document.getElementById('passwordModal');
        const passwordForm = document.getElementById('passwordForm');
        
        function openPasswordModal() {
            passwordModal.classList.add('open');
            // 关闭个人信息抽屉
            closeDrawer();
        }
        
        function closePasswordModal() {
            passwordModal.classList.remove('open');
            // 清空表单和错误信息
            passwordForm.reset();
            clearPasswordErrors();
        }
        
        function clearPasswordErrors() {
            document.getElementById('currentPasswordError').textContent = '';
            document.getElementById('newPasswordError').textContent = '';
            document.getElementById('confirmPasswordError').textContent = '';
        }
        
        function showPasswordError(fieldId, message) {
            document.getElementById(fieldId + 'Error').textContent = message;
        }
        
        function validatePassword() {
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            clearPasswordErrors();
            let isValid = true;
            
            // 验证当前密码（这里简化处理，实际应该与服务器验证）
            if (!currentPassword) {
                showPasswordError('currentPassword', '请输入当前密码');
                isValid = false;
            }
            
            // 验证新密码
            if (!newPassword) {
                showPasswordError('newPassword', '请输入新密码');
                isValid = false;
            } else if (newPassword.length < 6) {
                showPasswordError('newPassword', '密码长度至少6位');
                isValid = false;
            }
            
            // 验证确认密码
            if (!confirmPassword) {
                showPasswordError('confirmPassword', '请确认新密码');
                isValid = false;
            } else if (newPassword !== confirmPassword) {
                showPasswordError('confirmPassword', '两次输入的密码不一致');
                isValid = false;
            }
            
            return isValid;
        }
        
        // 事件监听
        document.getElementById('changePasswordBtn').addEventListener('click', openPasswordModal);
        document.getElementById('passwordClose').addEventListener('click', closePasswordModal);
        document.getElementById('passwordCancel').addEventListener('click', closePasswordModal);
        
        // 点击模态框背景关闭
        passwordModal.addEventListener('click', (e) => {
            if (e.target === passwordModal) {
                closePasswordModal();
            }
        });
        
        // 表单提交
        passwordForm.addEventListener('submit', (e) => {
            e.preventDefault();
            
            if (validatePassword()) {
                // 这里应该调用API修改密码
                alert('密码修改成功！');
                closePasswordModal();
            }
        });
        
        // Esc键关闭密码模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && passwordModal.classList.contains('open')) {
                closePasswordModal();
            }
        });

        // 自动翻转marquee-flip组
        (function(){
            const flip = document.getElementById('marqueeFlip');
            const groups = flip.querySelectorAll('.flip-group');
            let idx = 0;
            setInterval(()=>{
                groups[idx].classList.remove('active');
                idx = (idx+1)%groups.length;
                groups[idx].classList.add('active');
            }, 5000);
        })();

        // 场景管理入口预留
        document.getElementById('sceneManageBtn').addEventListener('click', () => {
            window.location.href = 'scene-manage.html';
        });

        // 横向滚动容器桌面拖曳增强
        function enableDesktopDragScroll(container){
            if(!container) return;
            let isMouseDown = false;
            let startX = 0;
            let startScrollLeft = 0;

            container.addEventListener('pointerdown', (e) => {
                if(e.pointerType !== 'mouse') return; // 保留触屏默认行为
                if(e.target.closest('button, a, input, label')) return;
                isMouseDown = true;
                startX = e.clientX;
                startScrollLeft = container.scrollLeft;
                container.classList.add('dragging');
                container.setPointerCapture(e.pointerId);
            });

            container.addEventListener('pointermove', (e) => {
                if(!isMouseDown) return;
                const delta = e.clientX - startX;
                container.scrollLeft = startScrollLeft - delta;
            });

            const endDrag = (e) => {
                if(isMouseDown && e.pointerType === 'mouse'){
                    container.classList.remove('dragging');
                    container.releasePointerCapture(e.pointerId);
                }
                isMouseDown = false;
            };

            container.addEventListener('pointerup', endDrag);
            container.addEventListener('pointerleave', endDrag);

            container.addEventListener('wheel', (e) => {
                if(Math.abs(e.deltaY) > Math.abs(e.deltaX)){
                    container.scrollLeft += e.deltaY;
                    e.preventDefault();
                }
            }, { passive:false });
        }

        enableDesktopDragScroll(document.querySelector('.scene-quick-scroll'));
        enableDesktopDragScroll(document.querySelector('.control-quick-scroll'));

        // 场景执行按钮提示
        document.querySelectorAll('.scene-card .scene-action').forEach(btn => {
            btn.addEventListener('click', (e) => {
                e.stopPropagation();
                const card = btn.closest('.scene-card');
                const sceneName = card?.dataset.scene || '场景';
                alert(`场景“${sceneName}”的执行命令已下发`);
            });
        });

        // 快捷数据管理功能
        (function(){
            const STORAGE_KEY = 'quickData';
            const dataQuickList = document.getElementById('dataQuickList');
            const dataManageModal = document.getElementById('dataManageModal');
            const dataSensorSelectModal = document.getElementById('dataSensorSelectModal');
            const manageDataList = document.getElementById('manageDataList');
            const dataSensorSelectList = document.getElementById('dataSensorSelectList');
            const dataSensorSearchInput = document.getElementById('dataSensorSearchInput');
            
            // 模拟数据传感器（实际应该从API获取）
            const availableDataSensors = [
                { id: '1', deviceName: '办公室', sensorName: '温度', type: 'temperature', unit: '℃', value: 24.5 },
                { id: '2', deviceName: '会议室', sensorName: '湿度', type: 'humidity', unit: '%', value: 55 },
                { id: '3', deviceName: '室外', sensorName: 'PM2.5', type: 'pm25', unit: 'μg/m³', value: 32 },
                { id: '4', deviceName: '室外', sensorName: 'PM10', type: 'pm10', unit: 'μg/m³', value: 48 },
                { id: '5', deviceName: '室内', sensorName: 'CO2浓度', type: 'co2', unit: 'ppm', value: 420 },
                { id: '6', deviceName: '车库', sensorName: 'CO浓度', type: 'co', unit: 'ppm', value: 8 },
                { id: '7', deviceName: '办公区', sensorName: '光照度', type: 'illuminance', unit: 'lux', value: 320 },
                { id: '8', deviceName: '室外', sensorName: '大气压', type: 'pressure', unit: 'hPa', value: 1013.2 },
                { id: '9', deviceName: '室外', sensorName: '风速', type: 'windSpeed', unit: 'm/s', value: 3.2 },
                { id: '10', deviceName: '设备间', sensorName: '噪声', type: 'noise', unit: 'dB', value: 45 },
                { id: '11', deviceName: '水箱', sensorName: '水位', type: 'waterLevel', unit: 'm', value: 2.8 },
                { id: '12', deviceName: '供水', sensorName: '流量', type: 'flow', unit: 'L/min', value: 12.5 },
                { id: '13', deviceName: '主电路', sensorName: '电压', type: 'voltage', unit: 'V', value: 220.5 },
                { id: '14', deviceName: '主电路', sensorName: '电流', type: 'current', unit: 'A', value: 15.8 },
                { id: '15', deviceName: '设备', sensorName: '总功率', type: 'power', unit: 'kW', value: 3.48 },
            ];
            
            // 生成显示名称
            function getDisplayName(item){
                return `${item.deviceName}${item.sensorName}`;
            }
            
            // 获取保存的数据列表
            function getDataItems(){
                const saved = localStorage.getItem(STORAGE_KEY);
                if(saved){
                    try{
                        return JSON.parse(saved);
                    }catch(e){
                        console.error('解析数据列表失败', e);
                    }
                }
                // 默认数据列表
                return [
                    { id: '1', deviceName: '办公室', sensorName: '温度', type: 'temperature', unit: '℃', value: 24.5 },
                    { id: '2', deviceName: '会议室', sensorName: '湿度', type: 'humidity', unit: '%', value: 55 },
                    { id: '3', deviceName: '室外', sensorName: 'PM2.5', type: 'pm25', unit: 'μg/m³', value: 32 },
                ];
            }
            
            // 保存数据列表
            function saveDataItems(items){
                localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
            }
            
            // 更新数据值（模拟实时数据变化）
            function updateDataValues(){
                const items = getDataItems();
                if(items.length === 0) return;
                
                // 定义各种数据类型的变化范围
                const valueRanges = {
                    'temperature': { min: 18, max: 30, variance: 0.5 }, // 温度：18-30℃，变化±0.5
                    'humidity': { min: 30, max: 80, variance: 2 }, // 湿度：30-80%，变化±2
                    'pm25': { min: 10, max: 150, variance: 3 }, // PM2.5：10-150 μg/m³，变化±3
                    'pm10': { min: 20, max: 200, variance: 4 }, // PM10：20-200 μg/m³，变化±4
                    'co2': { min: 300, max: 1000, variance: 10 }, // CO2：300-1000 ppm，变化±10
                    'co': { min: 0, max: 50, variance: 1 }, // CO：0-50 ppm，变化±1
                    'illuminance': { min: 100, max: 1000, variance: 20 }, // 光照度：100-1000 lux，变化±20
                    'pressure': { min: 980, max: 1050, variance: 1 }, // 大气压：980-1050 hPa，变化±1
                    'windSpeed': { min: 0, max: 15, variance: 0.5 }, // 风速：0-15 m/s，变化±0.5
                    'noise': { min: 30, max: 80, variance: 2 }, // 噪声：30-80 dB，变化±2
                    'waterLevel': { min: 1, max: 5, variance: 0.1 }, // 水位：1-5 m，变化±0.1
                    'flow': { min: 5, max: 50, variance: 1 }, // 流量：5-50 L/min，变化±1
                    'voltage': { min: 210, max: 230, variance: 0.5 }, // 电压：210-230 V，变化±0.5
                    'current': { min: 5, max: 30, variance: 0.5 }, // 电流：5-30 A，变化±0.5
                    'power': { min: 1, max: 10, variance: 0.2 }, // 功率：1-10 kW，变化±0.2
                };
                
                let hasUpdate = false;
                items.forEach(item => {
                    const range = valueRanges[item.type];
                    if(range){
                        // 在当前值基础上随机变化，但保持在合理范围内
                        const change = (Math.random() - 0.5) * 2 * range.variance;
                        let newValue = item.value + change;
                        
                        // 确保值在合理范围内
                        newValue = Math.max(range.min, Math.min(range.max, newValue));
                        
                        // 根据单位保留适当的小数位
                        if(item.unit === 'kW'){
                            newValue = Math.round(newValue * 100) / 100; // 保留2位小数
                        }else if(item.unit === '℃' || item.unit === 'm' || item.unit === 'V' || item.unit === 'A' || item.unit === 'm/s' || item.unit === 'hPa'){
                            newValue = Math.round(newValue * 10) / 10; // 保留1位小数
                        }else{
                            newValue = Math.round(newValue); // 整数
                        }
                        
                        if(Math.abs(newValue - item.value) > 0.01){ // 只有变化明显时才更新
                            item.value = newValue;
                            hasUpdate = true;
                        }
                    }
                });
                
                if(hasUpdate){
                    saveDataItems(items);
                    renderDataList(true); // 重新渲染列表以显示新值，并触发更新动画
                }
            }
            
            // 渲染数据列表
            let previousValues = new Map(); // 存储上一次的值用于检测变化
            
            function renderDataList(showUpdateAnimation = false){
                const items = getDataItems();
                dataQuickList.innerHTML = '';
                
                if(items.length === 0){
                    dataQuickList.innerHTML = '<div style="text-align:center; padding:40px; color:var(--subtext);">暂无数据</div>';
                    previousValues.clear();
                    return;
                }
                
                // 如果显示更新动画，先给整个列表添加动画类
                if(showUpdateAnimation){
                    dataQuickList.classList.add('updating');
                    setTimeout(() => {
                        dataQuickList.classList.remove('updating');
                    }, 1000);
                }
                
                items.forEach((item, index) => {
                    const row = document.createElement('div');
                    row.className = 'data-row';
                    
                    const valueEl = document.createElement('span');
                    valueEl.className = 'data-value';
                    valueEl.textContent = `${item.value} ${item.unit}`;
                    
                    const nameEl = document.createElement('span');
                    nameEl.className = 'data-name';
                    nameEl.textContent = getDisplayName(item);
                    
                    row.appendChild(nameEl);
                    row.appendChild(valueEl);
                    
                    // 检测值是否发生变化，如果变化则添加动画
                    const itemKey = `${item.id}_${item.type}`;
                    const prevValue = previousValues.get(itemKey);
                    const currentValue = item.value;
                    
                    if(showUpdateAnimation && prevValue !== undefined && Math.abs(prevValue - currentValue) > 0.01){
                        // 值有变化，添加更新动画
                        row.classList.add('updating');
                        valueEl.classList.add('updating');
                        
                        // 动画结束后移除类
                        setTimeout(() => {
                            row.classList.remove('updating');
                            valueEl.classList.remove('updating');
                        }, 800);
                    }
                    
                    // 更新存储的值
                    previousValues.set(itemKey, currentValue);
                    
                    dataQuickList.appendChild(row);
                });
            }
            
            // 渲染管理数据列表
            function renderManageDataList(){
                const items = getDataItems();
                manageDataList.innerHTML = '';
                
                if(items.length === 0){
                    manageDataList.innerHTML = '<div style="text-align:center; padding:40px; color:var(--subtext);">暂无数据</div>';
                    return;
                }
                
                items.forEach((item, index) => {
                    const manageItem = document.createElement('div');
                    manageItem.className = 'manage-control-item';
                    manageItem.innerHTML = `
                        <div class="manage-control-info">
                            <div class="manage-control-name">${getDisplayName(item)}</div>
                            <div class="manage-control-type">${item.deviceName} - ${item.sensorName}</div>
                        </div>
                        <button type="button" class="manage-control-delete" data-index="${index}">×</button>
                    `;
                    const deleteBtn = manageItem.querySelector('.manage-control-delete');
                    deleteBtn.addEventListener('click', () => {
                        deleteDataItem(index);
                    });
                    manageDataList.appendChild(manageItem);
                });
            }
            
            // 渲染数据传感器选择列表
            function renderDataSensorList(searchText = ''){
                const items = getDataItems();
                const addedIds = new Set(items.map(item => item.id));
                
                const filtered = searchText 
                    ? availableDataSensors.filter(sensor => {
                        const displayName = getDisplayName(sensor);
                        return displayName.toLowerCase().includes(searchText.toLowerCase()) ||
                               sensor.deviceName.toLowerCase().includes(searchText.toLowerCase()) ||
                               sensor.sensorName.toLowerCase().includes(searchText.toLowerCase());
                    })
                    : availableDataSensors;
                
                dataSensorSelectList.innerHTML = '';
                
                if(filtered.length === 0){
                    dataSensorSelectList.innerHTML = '<div style="text-align:center; padding:40px; color:var(--subtext);">未找到数据传感器</div>';
                    return;
                }
                
                filtered.forEach(sensor => {
                    const item = document.createElement('div');
                    item.className = 'device-select-item';
                    if(addedIds.has(sensor.id)){
                        item.classList.add('disabled');
                    }
                    
                    item.innerHTML = `
                        <div class="device-select-name">${getDisplayName(sensor)}</div>
                        <div class="device-select-controls">
                            <span class="device-control-badge">${sensor.deviceName}</span>
                            <span class="device-control-badge">${sensor.sensorName}</span>
                        </div>
                    `;
                    
                    if(!addedIds.has(sensor.id)){
                        item.addEventListener('click', () => {
                            addDataItem(sensor);
                            closeModal('dataSensorSelectModal');
                        });
                    }
                    
                    dataSensorSelectList.appendChild(item);
                });
            }
            
            // 添加数据项
            function addDataItem(sensor){
                const items = getDataItems();
                const wasEmpty = items.length === 0;
                items.push(sensor);
                saveDataItems(items);
                renderDataList();
                renderManageDataList();
                
                // 如果从空列表添加第一个项，启动定时器
                if(wasEmpty){
                    startDataUpdateTimer();
                }
                
                alert(`已添加数据：${getDisplayName(sensor)}`);
            }
            
            // 删除数据项
            function deleteDataItem(index){
                const items = getDataItems();
                const deleted = items.splice(index, 1)[0];
                const isEmpty = items.length === 0;
                saveDataItems(items);
                renderDataList();
                renderManageDataList();
                
                // 如果删除后列表为空，停止定时器
                if(isEmpty){
                    stopDataUpdateTimer();
                }
                
                alert(`已删除数据：${getDisplayName(deleted)}`);
            }
            
            // 打开/关闭弹窗
            function openModal(id){
                const modal = document.getElementById(id);
                if(modal) modal.classList.add('open');
            }
            
            function closeModal(id){
                const modal = document.getElementById(id);
                if(modal) modal.classList.remove('open');
            }
            
            // 事件监听
            document.getElementById('dataManageBtn').addEventListener('click', () => {
                renderManageDataList();
                openModal('dataManageModal');
            });
            
            document.getElementById('addDataBtn').addEventListener('click', () => {
                closeModal('dataManageModal');
                dataSensorSearchInput.value = '';
                renderDataSensorList();
                openModal('dataSensorSelectModal');
            });
            
            // 数据传感器搜索
            dataSensorSearchInput.addEventListener('input', (e) => {
                renderDataSensorList(e.target.value);
            });
            
            // 关闭弹窗按钮
            document.querySelectorAll('[data-close]').forEach(btn => {
                if(['dataManageModal', 'dataSensorSelectModal'].includes(btn.dataset.close)){
                    btn.addEventListener('click', () => {
                        closeModal(btn.dataset.close);
                    });
                }
            });
            
            // 点击遮罩关闭弹窗
            [dataManageModal, dataSensorSelectModal].forEach(modal => {
                if(modal){
                    modal.addEventListener('click', (e) => {
                        if(e.target === modal) closeModal(modal.id);
                    });
                }
            });
            
            // 定时更新数据值
            let dataUpdateTimer = null;
            
            function startDataUpdateTimer(){
                // 清除已有定时器
                if(dataUpdateTimer){
                    clearInterval(dataUpdateTimer);
                }
                
                // 每10秒更新一次数据值
                dataUpdateTimer = setInterval(() => {
                    const items = getDataItems();
                    if(items.length > 0){
                        updateDataValues();
                    }
                }, 10000); // 10秒 = 10000毫秒
            }
            
            function stopDataUpdateTimer(){
                if(dataUpdateTimer){
                    clearInterval(dataUpdateTimer);
                    dataUpdateTimer = null;
                }
            }
            
            // 页面可见性变化时控制定时器（优化性能）
            document.addEventListener('visibilitychange', () => {
                if(document.hidden){
                    stopDataUpdateTimer();
                }else{
                    const items = getDataItems();
                    if(items.length > 0){
                        startDataUpdateTimer();
                    }
                }
            });
            
            // 初始化渲染和启动定时器
            const initialItems = getDataItems();
            if(initialItems.length > 0){
                // 初始化previousValues，记录初始值
                initialItems.forEach(item => {
                    const itemKey = `${item.id}_${item.type}`;
                    previousValues.set(itemKey, item.value);
                });
            }
            renderDataList(); // 初始渲染不显示动画
            if(initialItems.length > 0){
                startDataUpdateTimer();
            }
            
            // 页面卸载时清除定时器
            window.addEventListener('beforeunload', () => {
                stopDataUpdateTimer();
            });
        })();

        // 快捷控制管理功能
        (function(){
            const STORAGE_KEY = 'quickControls';
            const controlQuickScroll = document.getElementById('controlQuickScroll');
            const controlManageModal = document.getElementById('controlManageModal');
            const deviceSelectModal = document.getElementById('deviceSelectModal');
            const manageControlList = document.getElementById('manageControlList');
            const deviceSelectList = document.getElementById('deviceSelectList');
            const deviceSearchInput = document.getElementById('deviceSearchInput');
            
            // 模拟设备数据（实际应该从API获取）
            // 获取设备的数据传感器（按设备ID）
            function getDeviceDataSensors(deviceId){
                const deviceDataMap = {
                    '1': [ // 办公室照明
                        { id: 'd1', name: '开关状态', type: 'switch_status', value: 'on' }
                    ],
                    '2': [ // 办公室空调
                        { id: 'd2', name: '运行状态', type: 'switch_status', value: 'off' },
                        { id: 'd3', name: '温度', type: 'temperature', value: 25 }
                    ],
                    '3': [ // 会议室窗帘
                        { id: 'd4', name: '开度', type: 'opening', value: 50 }
                    ],
                    '4': [ // 走廊灯光
                        { id: 'd5', name: '开关状态', type: 'switch_status', value: 'off' },
                        { id: 'd6', name: '亮度', type: 'brightness', value: 80 }
                    ],
                    '5': [ // 会议室空调
                        { id: 'd7', name: '运行状态', type: 'switch_status', value: 'on' },
                        { id: 'd8', name: '温度', type: 'temperature', value: 26 }
                    ],
                    '6': [ // 窗户控制器
                        { id: 'd9', name: '开度', type: 'opening', value: 0 }
                    ],
                    '7': [ // 前台照明
                        { id: 'd10', name: '开关状态', type: 'switch_status', value: 'on' },
                        { id: 'd11', name: '亮度', type: 'brightness', value: 60 }
                    ],
                    '8': [ // 主办公室空调
                        { id: 'd12', name: '运行状态', type: 'switch_status', value: 'off' },
                        { id: 'd13', name: '温度', type: 'temperature', value: 24 }
                    ]
                };
                return deviceDataMap[deviceId] || [];
            }
            
            const availableDevices = [
                { id: '1', name: '办公室照明', controls: ['switch'] },
                { id: '2', name: '办公室空调', controls: ['aircon'] },
                { id: '3', name: '会议室窗帘', controls: ['opening'] },
                { id: '4', name: '走廊灯光', controls: ['switch', 'brightness'] },
                { id: '5', name: '会议室空调', controls: ['aircon'] },
                { id: '6', name: '窗户控制器', controls: ['opening'] },
                { id: '7', name: '前台照明', controls: ['switch', 'brightness'] },
                { id: '8', name: '主办公室空调', controls: ['aircon'] },
            ];
            
            const typeNames = {
                'switch': '开关控制',
                'aircon': '红外遥控器控制面板',
                'opening': '开度控制',
                'brightness': '亮度控制'
            };
            
            // 获取保存的控制列表
            function getControls(){
                const saved = localStorage.getItem(STORAGE_KEY);
                if(saved){
                    try{
                        const controls = JSON.parse(saved);
                        // 确保每个控制都有 statusData 和 controlName 字段（向后兼容）
                        return controls.map(control => {
                            if(!control.hasOwnProperty('statusData')){
                                control.statusData = null;
                            }
                            if(!control.hasOwnProperty('controlName')){
                                control.controlName = typeNames[control.type] || control.type;
                            }
                            return control;
                        });
                    }catch(e){
                        console.error('解析控制列表失败', e);
                    }
                }
                // 默认控制列表
                return [
                    { id: '1', name: '办公室照明', controlName: '开关控制', type: 'switch', statusData: { id: 'd1', name: '开关状态', type: 'switch_status', value: 'on' } },
                    { id: '2', name: '办公室空调', controlName: '红外遥控器控制面板', type: 'aircon', statusData: null },
                    { id: '3', name: '会议室窗帘', controlName: '开度控制', type: 'opening', statusData: null }
                ];
            }
            
            // 保存控制列表
            function saveControls(controls){
                localStorage.setItem(STORAGE_KEY, JSON.stringify(controls));
            }
            
            // 渲染控制卡片
            function renderControlCards(){
                const controls = getControls();
                controlQuickScroll.innerHTML = '';
                
                controls.forEach((control, index) => {
                    const card = document.createElement('div');
                    card.className = 'control-card';
                    card.setAttribute('data-name', control.name);
                    card.setAttribute('data-type', control.type);
                    
                    // 显示设备名、控制器名和控制类型
                    const controlName = control.controlName || '';
                    const typeName = typeNames[control.type] || control.type;
                    // 如果控制器名存在且不等于类型名，则同时显示；否则只显示类型名
                    const subtitle = controlName && controlName !== typeName 
                        ? `${controlName} - ${typeName}` 
                        : typeName;
                    card.innerHTML = `
                        <div class="control-title">${control.name}</div>
                        <div class="control-subtitle">${subtitle}</div>
                        <div class="control-footer">
                            <button type="button" class="control-btn" data-control-index="${index}">下发命令</button>
                        </div>
                    `;
                    
                    // 绑定下发命令按钮
                    const btn = card.querySelector('.control-btn');
                    btn.addEventListener('click', () => {
                        if(window.openControlPanelWithState){
                            window.openControlPanelWithState(control);
                        } else {
                            alert('控制面板未初始化，请刷新页面重试');
                        }
                    });
                    
                    controlQuickScroll.appendChild(card);
                });
                
                // 重新启用拖拽滚动
                enableDesktopDragScroll(controlQuickScroll);
            }
            
            // 渲染管理控制列表
            function renderManageList(){
                const controls = getControls();
                manageControlList.innerHTML = '';
                
                if(controls.length === 0){
                    manageControlList.innerHTML = '<div style="text-align:center; padding:40px; color:var(--subtext);">暂无控制设备</div>';
                    return;
                }
                
                controls.forEach((control, index) => {
                    const item = document.createElement('div');
                    item.className = 'manage-control-item';
                    item.innerHTML = `
                        <div class="manage-control-info">
                            <div class="manage-control-name">${control.name}</div>
                            <div class="manage-control-type">类型：${typeNames[control.type] || control.type}</div>
                        </div>
                        <button type="button" class="manage-control-delete" data-index="${index}">×</button>
                    `;
                    const deleteBtn = item.querySelector('.manage-control-delete');
                    deleteBtn.addEventListener('click', () => {
                        deleteControl(index);
                    });
                    manageControlList.appendChild(item);
                });
            }
            
            // 渲染设备选择列表
            function renderDeviceList(searchText = ''){
                const controls = getControls();
                const addedDeviceIds = new Set(controls.map(c => {
                    // 提取原始设备id（去掉控制类型后缀）
                    return c.id.split('_')[0];
                }));
                
                const filtered = searchText 
                    ? availableDevices.filter(d => d.name.toLowerCase().includes(searchText.toLowerCase()))
                    : availableDevices;
                
                deviceSelectList.innerHTML = '';
                
                if(filtered.length === 0){
                    deviceSelectList.innerHTML = '<div style="text-align:center; padding:40px; color:var(--subtext);">未找到设备</div>';
                    return;
                }
                
                filtered.forEach(device => {
                    const isFullyAdded = addedDeviceIds.has(device.id) && 
                        device.controls.every(ctrl => {
                            const controlKey = `${device.id}_${ctrl}`;
                            return controls.some(c => c.id === device.id || c.id === controlKey);
                        });
                    
                    const item = document.createElement('div');
                    item.className = 'device-select-item';
                    if(isFullyAdded){
                        item.classList.add('disabled');
                    }
                    
                    const controlsHtml = device.controls.map(ctrl => {
                        const controlKey = `${device.id}_${ctrl}`;
                        const isAdded = controls.some(c => c.id === device.id && c.type === ctrl || c.id === controlKey);
                        return `<span class="device-control-badge" style="${isAdded ? 'opacity:0.5; text-decoration:line-through;' : ''}">${typeNames[ctrl] || ctrl}</span>`;
                    }).join('');
                    
                    item.innerHTML = `
                        <div class="device-select-name">${device.name}</div>
                        <div class="device-select-controls">${controlsHtml}</div>
                    `;
                    
                    if(!isFullyAdded){
                        item.addEventListener('click', () => {
                            selectDeviceControl(device);
                        });
                    }
                    
                    deviceSelectList.appendChild(item);
                });
            }
            
            // 选择设备控制（弹出控制类型选择）
            function selectDeviceControl(device){
                const controls = getControls();
                // 过滤出未添加的控制类型
                const availableControls = device.controls.filter(ctrl => {
                    const controlKey = `${device.id}_${ctrl}`;
                    return !controls.some(c => (c.id === device.id && c.type === ctrl) || c.id === controlKey);
                });
                
                if(availableControls.length === 0){
                    alert('该设备的所有控制类型已添加');
                    return;
                }
                
                // 选择控制类型后的回调
                function onControlTypeSelected(type){
                    // 关闭控制类型选择弹窗（如果存在）
                    const selectTypeModal = document.getElementById('selectTypeModal');
                    if(selectTypeModal) selectTypeModal.remove();
                    
                    // 弹出数据选择步骤
                    selectStatusData(device, type);
                }
                
                if(availableControls.length === 1){
                    // 只有一个未添加的控制类型，直接选择数据
                    onControlTypeSelected(availableControls[0]);
                }else{
                    // 多个控制类型，创建选择弹窗
                    const selectTypeModal = document.createElement('div');
                    selectTypeModal.className = 'modal-mask open';
                    selectTypeModal.id = 'selectTypeModal';
                    selectTypeModal.innerHTML = `
                        <div class="modal-dialog" style="max-width:380px;">
                            <div class="modal-header">
                                <div class="modal-title">选择控制类型</div>
                                <button class="modal-close" onclick="this.closest('.modal-mask').remove()">×</button>
                            </div>
                            <div class="modal-body">
                                <div style="margin-bottom:12px; color:var(--subtext);">请选择"${device.name}"的控制类型：</div>
                                ${availableControls.map(ctrl => `
                                    <button class="modal-btn" style="margin-bottom:10px; width:100%;" data-type="${ctrl}">
                                        ${typeNames[ctrl] || ctrl}
                                    </button>
                                `).join('')}
                            </div>
                            <div class="modal-footer">
                                <button class="modal-btn" onclick="this.closest('.modal-mask').remove()" style="flex:1;">取消</button>
                            </div>
                        </div>
                    `;
                    document.body.appendChild(selectTypeModal);
                    
                    // 绑定控制类型选择
                    selectTypeModal.querySelectorAll('[data-type]').forEach(btn => {
                        btn.addEventListener('click', () => {
                            const type = btn.dataset.type;
                            onControlTypeSelected(type);
                        });
                    });
                    
                    // 点击遮罩关闭
                    selectTypeModal.addEventListener('click', (e) => {
                        if(e.target === selectTypeModal) selectTypeModal.remove();
                    });
                }
            }
            
            // 选择状态数据（可选）
            function selectStatusData(device, controlType){
                const allDataSensors = getDeviceDataSensors(device.id);
                
                // 根据控制器类型过滤数据
                let filteredDataSensors = [];
                let promptText = '';
                
                if(controlType === 'switch'){
                    // 开关类：需要 switch_status 类型
                    filteredDataSensors = allDataSensors.filter(s => s.type === 'switch_status');
                    promptText = '该控制器为开关类型，请绑定一个开关参考数据。可不选。';
                } else if(controlType === 'opening' || controlType === 'brightness'){
                    // 开度/亮度类：需要对应类型
                    filteredDataSensors = allDataSensors.filter(s => s.type === controlType);
                    const typeName = controlType === 'opening' ? '开度' : '亮度';
                    promptText = `该控制器为${typeName}类型，请绑定一个${typeName}参考数据。可不选。`;
                } else if(controlType === 'aircon'){
                    // 空调类：需要 temperature 类型
                    filteredDataSensors = allDataSensors.filter(s => s.type === 'temperature');
                    promptText = '该控制器为红外遥控器控制面板，不能获取实时控制数据。请绑定一个温度参考数据。可不选。';
                }
                
                // 如果没有匹配的数据传感器，直接添加控制
                if(filteredDataSensors.length === 0){
                    addControl({
                        id: device.id + (device.controls.length > 1 ? '_' + controlType : ''),
                        name: device.name,
                        controlName: typeNames[controlType] || controlType,
                        type: controlType,
                        statusData: null
                    });
                    closeModal('deviceSelectModal');
                    return;
                }
                
                // 创建数据选择弹窗
                const selectDataModal = document.createElement('div');
                selectDataModal.className = 'modal-mask open';
                selectDataModal.id = 'selectDataModal';
                selectDataModal.innerHTML = `
                    <div class="modal-dialog" style="max-width:380px;">
                        <div class="modal-header">
                            <div class="modal-title">绑定参考数据</div>
                            <button class="modal-close" onclick="this.closest('.modal-mask').remove()">×</button>
                        </div>
                        <div class="modal-body">
                            <div style="margin-bottom:12px; color:var(--subtext);">${promptText}</div>
                            <button class="modal-btn" style="margin-bottom:10px; width:100%;" data-data-id="none">
                                不选择
                            </button>
                            ${filteredDataSensors.map(sensor => {
                                let displayValue = '';
                                if(sensor.type === 'switch_status'){
                                    displayValue = sensor.value === 'on' ? '开启' : '关闭';
                                } else if(sensor.type === 'opening' || sensor.type === 'brightness'){
                                    displayValue = sensor.value + (sensor.type === 'opening' ? '%' : '%');
                                } else if(sensor.type === 'temperature'){
                                    displayValue = sensor.value + '°C';
                                } else {
                                    displayValue = sensor.value;
                                }
                                return `
                                    <button class="modal-btn" style="margin-bottom:10px; width:100%;" data-data-id="${sensor.id}" data-data-type="${sensor.type}" data-data-value="${sensor.value}">
                                        ${sensor.name} (${displayValue})
                                    </button>
                                `;
                            }).join('')}
                        </div>
                        <div class="modal-footer">
                            <button class="modal-btn" onclick="this.closest('.modal-mask').remove()" style="flex:1;">取消</button>
                        </div>
                    </div>
                `;
                document.body.appendChild(selectDataModal);
                
                // 绑定数据选择
                selectDataModal.querySelectorAll('[data-data-id]').forEach(btn => {
                    btn.addEventListener('click', () => {
                        const dataId = btn.dataset.dataId;
                        let statusData = null;
                        
                        if(dataId !== 'none'){
                            statusData = {
                                id: dataId,
                                name: btn.textContent.split(' (')[0],
                                type: btn.dataset.dataType,
                                value: btn.dataset.dataValue
                            };
                        }
                        
                        addControl({
                            id: device.id + (device.controls.length > 1 ? '_' + controlType : ''),
                            name: device.name,
                            controlName: typeNames[controlType] || controlType,
                            type: controlType,
                            statusData: statusData
                        });
                        
                        selectDataModal.remove();
                        closeModal('deviceSelectModal');
                    });
                });
                
                // 点击遮罩关闭
                selectDataModal.addEventListener('click', (e) => {
                    if(e.target === selectDataModal) selectDataModal.remove();
                });
            }
            
            // 添加控制
            function addControl(control){
                const controls = getControls();
                controls.push(control);
                saveControls(controls);
                renderControlCards();
                renderManageList();
                alert(`已添加控制：${control.name}`);
            }
            
            // 删除控制
            function deleteControl(index){
                const controls = getControls();
                const deleted = controls.splice(index, 1)[0];
                saveControls(controls);
                renderControlCards();
                renderManageList();
                alert(`已删除控制：${deleted.name}`);
            }
            
            // 打开/关闭弹窗
            function openModal(id){
                const modal = document.getElementById(id);
                if(modal) modal.classList.add('open');
            }
            
            function closeModal(id){
                const modal = document.getElementById(id);
                if(modal) modal.classList.remove('open');
            }
            
            // 打开控制面板（复用之前的函数）
            function openControlPanel(type, name){
                // 这个函数会在控制面板逻辑中定义
                window.openControlPanel?.(type, name);
            }
            
            // 事件监听
            document.getElementById('controlManageBtn').addEventListener('click', () => {
                renderManageList();
                openModal('controlManageModal');
            });
            
            document.getElementById('addControlBtn').addEventListener('click', () => {
                closeModal('controlManageModal');
                deviceSearchInput.value = '';
                renderDeviceList();
                openModal('deviceSelectModal');
            });
            
            // 设备搜索
            deviceSearchInput.addEventListener('input', (e) => {
                renderDeviceList(e.target.value);
            });
            
            // 关闭弹窗按钮
            document.querySelectorAll('[data-close]').forEach(btn => {
                btn.addEventListener('click', () => {
                    closeModal(btn.dataset.close);
                });
            });
            
            // 点击遮罩关闭弹窗
            [controlManageModal, deviceSelectModal].forEach(modal => {
                if(modal){
                    modal.addEventListener('click', (e) => {
                        if(e.target === modal) closeModal(modal.id);
                    });
                }
            });
            
            // 初始化渲染
            renderControlCards();
        })();

        // 控制面板逻辑
        (function(){
            const switchModal = document.getElementById('switchModal');
            const airconModal = document.getElementById('airconModal');
            const openingModal = document.getElementById('openingModal');
            const brightnessModal = document.getElementById('brightnessModal');

            let switchState = null;
            let airconState = { power:'off', temp:25, mode:'cool' };
            let openingPercent = 0;
            let brightnessPercent = 0;
            let currentControllerName = '';
            
            // 亮度控制拖动相关变量
            let brightnessIsDragging = false;
            let brightnessLastCommandValue = 0;
            let brightnessDragInitialized = false;

            // 打开控制面板并初始化状态
            window.openControlPanelWithState = function(control){
                currentControllerName = control.name;
                
                if(control.type === 'switch'){
                    // 开关类：按绑定状态初始化，没有则默认关闭
                    if(control.statusData && control.statusData.type === 'switch_status'){
                        switchState = control.statusData.value === 'on' ? 'on' : 'off';
                    } else {
                        switchState = 'off'; // 默认关闭
                    }
                    
                    // 更新 switch 控件状态
                    const switchToggle = document.getElementById('switchToggle');
                    const switchStatus = document.getElementById('switchStatus');
                    if(switchToggle){
                        switchToggle.classList.remove('on', 'off');
                        switchToggle.classList.add(switchState);
                    }
                    if(switchStatus){
                        switchStatus.textContent = `当前状态：${switchState === 'on' ? '开启' : '关闭'}`;
                        switchStatus.style.color = switchState === 'on' ? 'var(--text)' : 'var(--subtext)';
                    }
                    
                    openModal('switchModal');
                } else if(control.type === 'opening' || control.type === 'brightness'){
                    // 开度/亮度类：按绑定参数初始化，没有则默认0
                    if(control.statusData && control.statusData.type === control.type){
                        const value = parseFloat(control.statusData.value) || 0;
                        if(control.type === 'opening'){
                            openingPercent = Math.max(0, Math.min(100, value));
                            updateOpeningUI();
                            openModal('openingModal');
                        } else {
                            brightnessPercent = Math.max(0, Math.min(100, value));
                            updateBrightnessUI();
                            if(!brightnessDragInitialized){
                                initBrightnessDrag();
                            }
                            brightnessLastCommandValue = brightnessPercent;
                            openModal('brightnessModal');
                        }
                    } else {
                        // 默认0
                        if(control.type === 'opening'){
                            openingPercent = 0;
                            updateOpeningUI();
                            openModal('openingModal');
                        } else {
                            brightnessPercent = 0;
                            updateBrightnessUI();
                            if(!brightnessDragInitialized){
                                initBrightnessDrag();
                            }
                            brightnessLastCommandValue = brightnessPercent;
                            openModal('brightnessModal');
                        }
                    }
                } else if(control.type === 'aircon'){
                    // 空调类：只显示绑定的显示参数，没有则不显示，不需要初始化
                    airconState = { power:'off', temp:25, mode:'cool' };
                    
                    // 如果绑定了温度参数，显示它
                    if(control.statusData && control.statusData.type === 'temperature'){
                        const tempDisplay = document.getElementById('airconTempDisplay');
                        if(tempDisplay){
                            tempDisplay.textContent = `当前温度：${control.statusData.value}°C`;
                            tempDisplay.style.display = 'block';
                        }
                    } else {
                        const tempDisplay = document.getElementById('airconTempDisplay');
                        if(tempDisplay){
                            tempDisplay.style.display = 'none';
                        }
                    }
                    
                    updateAirconUI();
                    openModal('airconModal');
                } else {
                    alert('暂不支持的控制类型');
                }
            };
            
            // 更新全局openControlPanel函数
            window.openControlPanel = function(type, name){
                currentControllerName = name;
                if(type === 'switch'){
                    // 默认关闭状态
                    switchState = 'off';
                    
                    // 更新 switch 控件状态
                    const switchToggle = document.getElementById('switchToggle');
                    const switchStatus = document.getElementById('switchStatus');
                    if(switchToggle){
                        switchToggle.classList.remove('on', 'off');
                        switchToggle.classList.add('off');
                    }
                    if(switchStatus){
                        switchStatus.textContent = '当前状态：关闭';
                        switchStatus.style.color = 'var(--subtext)';
                    }
                    openModal('switchModal');
                }else if(type === 'aircon'){
                    airconState = { power:'off', temp:25, mode:'cool' };
                    updateAirconUI();
                    openModal('airconModal');
                }else if(type === 'opening'){
                    openingPercent = 0;
                    updateOpeningUI();
                    openModal('openingModal');
                }else if(type === 'brightness'){
                    brightnessPercent = 0;
                    updateBrightnessUI();
                    if(!brightnessDragInitialized){
                        initBrightnessDrag();
                    }
                    brightnessLastCommandValue = brightnessPercent;
                    openModal('brightnessModal');
                }else{
                    alert('暂不支持的控制类型');
                }
            };

            function openModal(id){
                const modal = document.getElementById(id);
                if(modal) modal.classList.add('open');
            }

            function closeModal(id){
                const modal = document.getElementById(id);
                if(modal) modal.classList.remove('open');
            }

            document.querySelectorAll('[data-close]').forEach(btn => {
                btn.addEventListener('click', () => closeModal(btn.dataset.close));
            });

            // Switch 切换功能
            const switchToggle = document.getElementById('switchToggle');
            if(switchToggle){
                switchToggle.addEventListener('click', function(){
                    const isOn = this.classList.contains('on');
                    const newState = isOn ? 'off' : 'on';
                    
                    // 更新状态
                    switchState = newState;
                    this.classList.remove('on', 'off');
                    this.classList.add(newState);
                    
                    // 更新状态文字
                    const switchStatus = document.getElementById('switchStatus');
                    if(switchStatus){
                        switchStatus.textContent = `当前状态：${newState === 'on' ? '开启' : '关闭'}`;
                        switchStatus.style.color = newState === 'on' ? 'var(--text)' : 'var(--subtext)';
                    }
                    
                    // 提示命令已发出
                    alert('命令已经发出');
                });
            }

            document.addEventListener('click', (e) => {
                const target = e.target;
                
                if(target.dataset.airconPower){
                    airconState.power = target.dataset.airconPower;
                    alert(`命令已下发：${airconState.power === 'on' ? '打开空调' : '关闭空调'}`);
                }

                if(target.dataset.airconTemp){
                    const delta = parseInt(target.dataset.airconTemp, 10);
                    airconState.temp = Math.max(16, Math.min(30, airconState.temp + delta));
                    updateAirconUI();
                }

                if(target.dataset.airconMode){
                    airconState.mode = target.dataset.airconMode;
                    updateAirconUI();
                }
            });


            document.getElementById('airconSaveBtn').addEventListener('click', () => {
                const modeText = airconState.mode === 'cool' ? '制冷' : '制热';
                alert(`红外遥控器控制面板命令已保存：${currentControllerName}，${airconState.power === 'on' ? '开启' : '关闭'}，${airconState.temp}°C，模式${modeText}`);
                closeModal('airconModal');
            });

            // 开度控制拖动功能
            let openingIsDragging = false;
            let openingLastCommandValue = 0;
            
            const openingTrack = document.getElementById('openingTrack');
            if(openingTrack){
                const openingHandle = document.getElementById('openingHandle');
                
                function updateOpening(clientX) {
                    const rect = openingTrack.getBoundingClientRect();
                    const x = clientX - rect.left;
                    const percentage = Math.round((x / rect.width) * 100);
                    const clampedPercentage = Math.max(0, Math.min(100, percentage));
                    
                    openingPercent = clampedPercentage;
                    updateOpeningUI();
                }
                
                function onStart(e) {
                    openingIsDragging = true;
                    e.preventDefault();
                    const clientX = e.touches ? e.touches[0].clientX : e.clientX;
                    updateOpening(clientX);
                }
                
                function onMove(e) {
                    if(!openingIsDragging) return;
                    e.preventDefault();
                    const clientX = e.touches ? e.touches[0].clientX : e.clientX;
                    updateOpening(clientX);
                }
                
                function onEnd(e) {
                    if(!openingIsDragging) return;
                    openingIsDragging = false;
                    // 拖动停止时，如果值发生变化，提示下发命令
                    if(openingPercent !== openingLastCommandValue){
                        alert(`命令已经发出：开度 ${openingPercent}%`);
                        openingLastCommandValue = openingPercent;
                    }
                }
                
                // 点击容器
                openingTrack.addEventListener('click', function(e) {
                    if(e.target === openingHandle) return;
                    const rect = openingTrack.getBoundingClientRect();
                    const x = e.clientX - rect.left;
                    const percentage = Math.round((x / rect.width) * 100);
                    const clampedPercentage = Math.max(0, Math.min(100, percentage));
                    openingPercent = clampedPercentage;
                    updateOpeningUI();
                    alert(`命令已经发出：开度 ${openingPercent}%`);
                    openingLastCommandValue = openingPercent;
                });
                
                // 鼠标拖动
                if(openingHandle){
                    openingHandle.addEventListener('mousedown', onStart);
                    document.addEventListener('mousemove', onMove);
                    document.addEventListener('mouseup', onEnd);
                    
                    // 触摸拖动
                    openingHandle.addEventListener('touchstart', onStart, {passive:false});
                    document.addEventListener('touchmove', onMove, {passive:false});
                    document.addEventListener('touchend', onEnd);
                }
            }

            
            // 亮度控制拖动功能初始化
            function initBrightnessDrag() {
                if(brightnessDragInitialized) return;
                brightnessDragInitialized = true;
                
                const brightnessContainer = document.getElementById('brightnessContainer');
                const brightnessHandle = document.getElementById('brightnessHandle');
                if(!brightnessContainer || !brightnessHandle) return;
                
                function updateBrightness(clientX) {
                    const rect = brightnessContainer.getBoundingClientRect();
                    const x = clientX - rect.left;
                    const percentage = Math.round((x / rect.width) * 100);
                    const clampedPercentage = Math.max(0, Math.min(100, percentage));
                    
                    brightnessPercent = clampedPercentage;
                    updateBrightnessUI();
                }
                
                function onStart(e) {
                    brightnessIsDragging = true;
                    e.preventDefault();
                    const clientX = e.touches ? e.touches[0].clientX : e.clientX;
                    updateBrightness(clientX);
                }
                
                function onMove(e) {
                    if(!brightnessIsDragging) return;
                    e.preventDefault();
                    const clientX = e.touches ? e.touches[0].clientX : e.clientX;
                    updateBrightness(clientX);
                }
                
                function onEnd(e) {
                    if(!brightnessIsDragging) return;
                    brightnessIsDragging = false;
                    // 拖动停止时，如果值发生变化，提示下发命令
                    if(brightnessPercent !== brightnessLastCommandValue){
                        alert(`命令已经发出：亮度 ${brightnessPercent}%`);
                        brightnessLastCommandValue = brightnessPercent;
                    }
                }
                
                // 点击容器
                brightnessContainer.addEventListener('click', function(e) {
                    if(e.target === brightnessHandle) return;
                    const rect = brightnessContainer.getBoundingClientRect();
                    const x = e.clientX - rect.left;
                    const percentage = Math.round((x / rect.width) * 100);
                    const clampedPercentage = Math.max(0, Math.min(100, percentage));
                    brightnessPercent = clampedPercentage;
                    updateBrightnessUI();
                    alert(`命令已经发出：亮度 ${brightnessPercent}%`);
                    brightnessLastCommandValue = brightnessPercent;
                });
                
                // 鼠标拖动
                brightnessHandle.addEventListener('mousedown', onStart);
                document.addEventListener('mousemove', onMove);
                document.addEventListener('mouseup', onEnd);
                
                // 触摸拖动
                brightnessHandle.addEventListener('touchstart', onStart, {passive:false});
                document.addEventListener('touchmove', onMove, {passive:false});
                document.addEventListener('touchend', onEnd);
            }
            
            // 页面加载时初始化亮度拖动功能
            setTimeout(() => {
                if(!brightnessDragInitialized){
                    initBrightnessDrag();
                }
            }, 100);

            function updateAirconUI(){
                document.getElementById('airconTemp').textContent = `${airconState.temp}°C`;
                document.getElementById('airconCoolBtn').classList.toggle('primary', airconState.mode === 'cool');
                document.getElementById('airconHeatBtn').classList.toggle('primary', airconState.mode === 'heat');
            }

            function updateOpeningUI(){
                document.getElementById('openingBar').style.width = `${openingPercent}%`;
                document.getElementById('openingHandle').style.left = `${openingPercent}%`;
                document.getElementById('openingValue').textContent = `${openingPercent}%`;
            }
            
            function updateBrightnessUI(){
                const brightnessBar = document.getElementById('brightnessBar');
                const brightnessHandle = document.getElementById('brightnessHandle');
                const brightnessValue = document.getElementById('brightnessValue');
                if(brightnessBar && brightnessHandle && brightnessValue){
                    brightnessBar.style.width = `${brightnessPercent}%`;
                    brightnessHandle.style.left = `${brightnessPercent}%`;
                    brightnessValue.textContent = `${brightnessPercent}%`;
                }
            }

            [switchModal, airconModal, openingModal, brightnessModal].forEach(modal => {
                if(!modal) return;
                modal.addEventListener('click', (e) => {
                    if(e.target === modal) modal.classList.remove('open');
                });
            });
        })();
    </script>
</body>
</html>

